import React, {
    Component,
} from 'react';

import { connect } from 'react-redux';

import {
    Animated,
    DeviceEventEmitter,
    BackHandler,
    View,
    Text,
    Image,
    ScrollView,
    TouchableWithoutFeedback,
    ViewPagerAndroid,
} from 'react-native';

import { chatroomLogin, chatroomLeave } from '../../actions/netease';
import { live_gift } from '../../actions/gift';
import { deepCopy } from '../../actions/helpers';
import NeteasePlayer from '../../components/NeteasePlayer/NeteasePlayer';
import GiftPlayer from '../../components/gift/GiftPlayer';
import {CachedImage} from "react-native-img-cache";

import styles from './css/detail';

class LiveDetail extends Component {

    static navigationOptions = {
        header: null,
    };

    constructor(props){
        super(props);
        this.state = {
            destory: false,
            msgList: new Array(),
            height1Anim: new Animated.Value(0), //底部浮层
            giftbox_showflg: false,
            height2Anim: new Animated.Value(300), //礼物浮层
            rtmpload_flg: false, //rtmp流是否已经加载完成
            gift_pnum: 8, //每页礼物数量
        };
        this._showGiftBox = this._showGiftBox.bind(this)
    }

    componentWillMount(){
        //返回键监听
        BackHandler.addEventListener('hardwareBackPress', this.handleBackPress);
        //登录聊天室
        chatroomLogin(this.props.navigation.getParam('chatRoomid'));
        //收到聊天消息
        DeviceEventEmitter.addListener('onChatroomMessage', (message) => {
            for(let i = 0; i < this.state.msgList.length; i++){
                if(this.state.msgList[i].time == message.time){
                    return false;
                }
            }
            this.state.msgList[this.state.msgList.length] = message;
            this.setState({
                msgList: this.state.msgList
            });
        });
        //rmtp 流加载成功
        DeviceEventEmitter.addListener('onRtmpFinish', () => this.setState({rtmpload_flg: true}));
    }

    componentDidMount(){
        //获取礼物列表
        if(this.props.liveGift.length == 0){
            live_gift(this.props.dispatch);
        }
    }

    componentWillUnmount() {
        BackHandler.removeEventListener('hardwareBackPress', this.handleBackPress);
        //离开聊天室
        chatroomLeave(this.props.navigation.getParam('chatRoomid'));
    }

    _showGiftBox(){
        this.setState({
            giftbox_showflg: true
        });
        Animated.parallel([
            Animated.timing(                  // 随时间变化而执行动画
                this.state.height1Anim,            // 动画中的变量值
                {
                  toValue: 45,                   // 透明度最终变为1，即完全不透明
                  duration: 100,              // 让动画持续一段时间
                }
            ),
            Animated.timing(                  // 随时间变化而执行动画
                this.state.height2Anim,            // 动画中的变量值
                {
                  toValue: 0,                   // 透明度最终变为1，即完全不透明
                  duration: 200,              // 让动画持续一段时间
                }
            )
        ]).start();
    }

    _hideGiftBox(){
        Animated.parallel([
            Animated.timing(                  // 随时间变化而执行动画
                this.state.height1Anim,            // 动画中的变量值
                {
                  toValue: 0,                   // 透明度最终变为1，即完全不透明
                  duration: 100,              // 让动画持续一段时间
                }
            ),
            Animated.timing(                  // 随时间变化而执行动画
                this.state.height2Anim,            // 动画中的变量值
                {
                  toValue: 300,                   // 透明度最终变为1，即完全不透明
                  duration: 200,              // 让动画持续一段时间
                }
            )
        ]).start(()=>{
            this.setState({
                giftbox_showflg: false
            });
        });
    }

    handleBackPress = () => {
        this.setState({
            destory: true
        });
        this.props.navigation.pop();
        return true;
    }

    render(){
        let msgList = deepCopy(this.state.msgList);
        msgList = msgList.splice(-10,10);
        return (
            <View style={styles.container}>
                <NeteasePlayer
                    src={this.props.navigation.getParam('source')}
                    destory={this.state.destory}
                    style={{flex: 1}}
                >
                </NeteasePlayer>
            { !this.state.rtmpload_flg || this.props.liveGift.length == 0 ?
                <Image style={styles.roomloading} resizeMode="stretch" source={require('./imgs/room_loading.png')} />
            : null }
                <View style={styles.containerInner}>
                    <View style={styles.bottomLine}>
                        <Animated.View style={[styles.bottomLineInner, {transform: [{translateY:this.state.height1Anim}]}]}>
                            <Image style={styles.bottomImg} resizeMode="stretch" source={require('./imgs/live_wheel_surf.png')} />
                            <TouchableWithoutFeedback
                                onPress={() => {
                                    this._showGiftBox();
                                }}
                            >
                                <Image style={styles.bottomImg} resizeMode="stretch" source={require('./imgs/live_send_gift.png')} />
                            </TouchableWithoutFeedback>
                        </Animated.View>
                    </View>
                    <View style={styles.msgList}>
                        <ScrollView>
                    {msgList.map((item,i) => {
                        return (
                            <View style={styles.row} key={item.time}>
                                <Text style={styles.msgRow}>
                                    <Text style={styles.nick}>{item.nickname+"："}</Text>
                                    <Text style={styles.content}>{item.content}</Text>
                                </Text>
                                <View style={{flex: 1}}></View>
                            </View>
                        )
                    })} 
                        </ScrollView>
                    </View>
                </View>
            {/** 礼物列表浮层 */}
            {this.state.giftbox_showflg && this.props.liveGift.length > 0 ? 
                <View style={styles.giftListBoxContainer}>
                    <TouchableWithoutFeedback
                        onPress={() => this._hideGiftBox()}
                    >
                        <View style={{flex: 1}}></View>
                    </TouchableWithoutFeedback>
                    <Animated.View style={[styles.giftListBox, {transform: [{translateY:this.state.height2Anim}]}]}>
                        <ViewPagerAndroid
                            style={{flex: 1}}
                            initialPage={0}>
                            {this.renderGift()}
                        </ViewPagerAndroid>
                    </Animated.View>
                </View>
            :null}
            {/** 礼物动画特效浮层 */}
                <GiftPlayer 
                    ref={giftplayer => {
                        this._giftplayer = giftplayer;
                    }}
                    giftAnim={this.props.giftAnim}
                />
            </View>
        )
    }

    renderGift(){
        var res = [];
        let pageNum = Math.ceil(this.props.liveGift.length/this.state.gift_pnum);
        for(var i = 0; i < pageNum; i++) {
          res.push(
            <View key={i+1} style={styles.giftboxpage}>
        {this.props.liveGift.slice(this.state.gift_pnum*i, this.state.gift_pnum*(i+1)).map((item2,i2) => {
            return (
                <View key={i2+1} style={styles.giftboxitem}>
                    <TouchableWithoutFeedback
                        onPress={() => this._giftplayer.play(item2.giftid)}
                    >
                        <CachedImage style={{width: 50, height: 50}} resizeMode="stretch" source={{uri: item2.giftUrl}} />
                    </TouchableWithoutFeedback>
                </View>
            )
        })}
            </View>
          )
        }
        return res
    }
}

function mapStateToProps(state) {
    return {
        giftAnim: state.gift.giftAnim,
        liveGift: state.gift.liveGift
    }
  }
  
  export default connect(mapStateToProps)(LiveDetail);